//
//  NSMutableDictionary+Safe.m
//  DebugDemo
//
//  Created by XFB on 2018/11/9.
//  Copyright © 2018年 ZhouCheng. All rights reserved.
//

#import "NSMutableDictionary+Safe.h"
#import "NSObject+Swizzling.h"

@implementation NSMutableDictionary (Safe)

+ (void)load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        // __NSPlaceholderDictionary 不行
        [objc_getClass("__NSDictionaryM") swizzleSelector:@selector(setObject:forKey:)
                                     withSwizzledSelector:@selector(zc_safeSetObject:forKey:)];
        
//        [objc_getClass("__NSDictionaryM") swizzleSelector:@selector(removeObjectForKey:)
//                                     withSwizzledSelector:@selector(zc_safeRemoveObjectForKey:)];
    });
}

//- (void)zc_safeRemoveObjectForKey:(NSString *)key
//{
//    if (!key) {
//        return;
//    }
//    [self zc_safeRemoveObjectForKey:key];
//}

- (void)zc_safeSetObject:(id)object forKey:(NSString *)key
{
    if (object == nil) {
        @try {
            [self zc_safeSetObject:object forKey:key];
        }
        @catch (NSException *exception) {
            NSLog(@"%@", [exception callStackSymbols]);
            object = @"";
            [self zc_safeSetObject:object forKey:key];
        }
        @finally {}
    } else {
        if (key == nil) {
            @try {
                [self zc_safeSetObject:object forKey:key];
            }
            @catch (NSException *exception) {
                NSLog(@"%@", [exception callStackSymbols]);
                return;
            }
            @finally {}
        } else {
            [self zc_safeSetObject:object forKey:key];
        }
    }
}

@end
